package com.plum.netty.demo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoop;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

public class HelloServer {
    public static void main(String[] args) {
        // 1. 启动器，负责组装 netty 组件，启动服务器
        new ServerBootstrap()
                // 2. 添加组件 NioEventLoopGroup = BossEventLoop + WorkerEventLoop(selector)
                .group(new NioEventLoopGroup())
                // 3. 选择serverSocket的实现
                .channel(NioServerSocketChannel.class)
                // 4. boss 负责处理连接 worker（chilld） 负责处理读写，决定了worker（child）能执行哪些操作（handler）
                .childHandler(
                        // 5. 代表和客户端进行数据读写的通过 Initializer 初始化，负责添加别的 Handler
                        new ChannelInitializer<NioSocketChannel>() {

                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        // 6. 添加具体的 Handler
                        ch.pipeline().addLast(new StringDecoder()); //将 ByteBuf 转为 字符串
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                super.channelRead(ctx, msg);
                                System.out.println(msg);
                            }
                        });
                    }
                })
                .bind(8080);
    }

}
